package com.ruoyi.web.controller.system;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 便民服务配置接口
 *
 * @author
 */
@RestController
@RequestMapping("/api/convenience")
public class ConvenienceServiceController extends BaseController
{
    private static final String CONFIG_KEY = "convenience.services";

    private static final String DEFAULT_CONFIG_JSON = "";

    @Autowired
    private ISysConfigService configService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取便民服务配置
     */
    @Anonymous
    @GetMapping("/services")
    public AjaxResult getConvenienceServices()
    {
        try
        {
            String configJson = configService.selectConfigByKey(CONFIG_KEY);
            Object configData = parseConfig(StringUtils.isNotEmpty(configJson) ? configJson : DEFAULT_CONFIG_JSON);
            return success(configData);
        }
        catch (Exception e)
        {
            logger.error("获取便民服务配置失败", e);
            try
            {
                return success(parseConfig(DEFAULT_CONFIG_JSON));
            }
            catch (Exception inner)
            {
                return error("获取便民服务配置失败：" + e.getMessage());
            }
        }
    }

    private Object parseConfig(String json) throws Exception
    {
        return objectMapper.readValue(json, Object.class);
    }
}

